/**
 * 数据统计
 */

import { Button, DatePicker, message, Radio, RadioChangeEvent } from "antd";
import { DataStaticPageBox } from "./style";
import { useCallback, useEffect, useMemo, useState } from "react";
import { DownloadOutlined } from '@ant-design/icons';
import dayjs from "dayjs";
import DataChart from "./components/DataChart";
import DataTable from "./components/DataTable";
import axios from "axios";
import { basicIp } from "../../../api/http";
import { IDataStatisticsParams, IDateCountGoodsPart, IDateCountGoodsStatus, IDateCountLoadingStatus, IDateCountShipCount } from "../../../type/DataStatistics/api";
import { getTlplTPeportSellProportion, getTlplTReportSellClient, getTlplTReportSellToday } from "../api";

const { RangePicker } = DatePicker;

const DataStaticdPage = () => {
    const [selectedRange, setSelectedRange] = useState<any>([dayjs(), dayjs()]);
    const [tpyeList, setTpyeList] = useState('0');

    const [datalistOne, setDatalistOne] = useState<IDateCountGoodsStatus[]>([])//品种销售情况
    const [datalistTwo, setDatalistTwo] = useState<IDateCountGoodsPart[]>([])//品种销售占比
    const [datalistThr, setDatalistThr] = useState<IDateCountShipCount[]>([])//客户发运量统计
    const [datalistFour, setDatalistFour] = useState<IDateCountLoadingStatus[]>([])//当日装车情况

    const parames: IDataStatisticsParams = useMemo(() => {
        return {
            startDate: selectedRange?.[0] ? dayjs(selectedRange?.[0]).format('YYYY-MM-DD') : undefined,
            endDate: selectedRange?.[1] ? dayjs(selectedRange?.[1]).format('YYYY-MM-DD') : undefined
        };
    }, [selectedRange]);

    //品种销售情况 品种销售占比
    const listFunOneTwo = useCallback(async () => {
        try {
            const { code, msg, data } = (await getTlplTPeportSellProportion(
                parames
            )) as {
                code: number
                msg: string
                data: {
                    id: string;
                    product: string;
                    proportion: number;
                    suttleCount: number;
                }[]
            }
            if (code === 20000) {
                let oneArr: IDateCountGoodsStatus[] = [];
                let twoArr: IDateCountGoodsPart[] = [];
                data.forEach((item, index) => {
                    const { id, suttleCount, proportion, product } = item
                    oneArr.push({
                        id: id,
                        suttleCount: suttleCount,//销售数量
                        product: product,

                    })
                    twoArr.push({
                        product: product,
                        proportion: proportion,
                        id: id
                    })

                })
                setDatalistOne(oneArr)
                setDatalistTwo(twoArr)
            } else {
                message.error(msg);
            }
        } catch (error) {
            message.error('网络请求失败')
        }
    }, [parames])
    //客户发运量统计
    const listFunThr = useCallback(async () => {
        try {
            const { code, msg, data } = (await getTlplTReportSellClient(
                parames
            )) as {
                code: number
                msg: string
                data: IDateCountShipCount[]
            }
            if (code === 20000) {
                setDatalistThr(data)
            } else {
                message.error(msg);
            }
        } catch (error) {
            message.error('网络请求失败')
        }
    }, [parames])
    //当日装车情况
    const listFunFour = useCallback(async () => {
        try {
            const { code, msg, data } = (await getTlplTReportSellToday(
                parames
            )) as {
                code: number
                msg: string
                data: IDateCountLoadingStatus[]
            }
            if (code === 20000) {
                setDatalistFour(data)
            } else {
                message.error(msg);
            }
        } catch (error) {
            message.error('网络请求失败')
        }
    }, [parames])
    useEffect(() => {
        listFunFour()
        listFunThr()
        listFunOneTwo()
    }, [listFunFour, listFunThr, listFunOneTwo])

    const handleChangeType = ({ target: { value } }: RadioChangeEvent) => {
        setTpyeList(value);
    };
    const handleButtonClick = (range: number) => {
        let startDate: dayjs.Dayjs;
        let endDate: dayjs.Dayjs;

        switch (range) {
            case 1: // 昨天
                startDate = dayjs().subtract(1, 'day').startOf('day');
                endDate = dayjs().subtract(1, 'day').endOf('day');
                break;
            case 7: // 近7天
                startDate = dayjs().subtract(6, 'day').startOf('day');
                endDate = dayjs().endOf('day');
                break;
            case 30: // 近30天
                startDate = dayjs().subtract(29, 'day').startOf('day');
                endDate = dayjs().endOf('day');
                break;
            default:
                startDate = dayjs().startOf('day');
                endDate = dayjs().endOf('day');
                break;
        }

        setSelectedRange([startDate, endDate]);
    };
    //导出
    const handleExportCallback = async () => {
        let params;
        if (selectedRange) {
            params = {
                startDate: dayjs(selectedRange[0]).format('YYYY-MM-DD'),
                endDate: dayjs(selectedRange[1]).format('YYYY-MM-DD'),
            };
        } else {
            params = {
                startDate: '',
                endDate: '',
            };
        }
        const token: string = sessionStorage.getItem("token") as string;
        axios({
            method: "post",
            url: basicIp + "/shipment/date-count/exportMultipleExcel",
            data: params,
            //重要：相应类型必须为blob
            responseType: "arraybuffer",
            headers: {
                token: token,
            },
        }).then((res) => {
            let fileRegex = /([^(filename=)]+\.xls?)$/g; //正则表达式 判断是否为xls结尾的excle表格
            var link = document.createElement("a"); //创建一个a标签
            //将文件流信息传入
            link.href = window.URL.createObjectURL(new Blob([res.data]));
            link.download = decodeURI(res.headers["content-disposition"]).match(
                fileRegex
            )![0];
            link.click(); //模拟点击a标签
            window.URL.revokeObjectURL(link.href);
        });
    };
    return (
        <DataStaticPageBox>
            <div className="title">
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div className="titleName">
                        数据统计
                    </div>
                    <Radio.Group
                        options={[{ label: '数据图表', value: '0' },
                        { label: '数据列表', value: '1' }]}
                        onChange={handleChangeType}
                        value={tpyeList}
                        optionType="button"
                        buttonStyle="solid"
                    />
                </div>
                <div className="titleRight">
                    <div className="title_right_xiazai"  style={{ display: 'flex', alignItems: 'center', color: '#999', cursor: 'pointer' }}
                        onClick={() => handleExportCallback()}
                    >
                        <DownloadOutlined />下载excl
                    </div>
                    <div style={{ marginLeft: '1.5rem', fontSize: '1.4rem' }}>
                        时间:
                        <Button type="link" onClick={() => handleButtonClick(1)}>昨天</Button>
                        <Button type="link" onClick={() => handleButtonClick(7)}>近7天</Button>
                        <Button type="link" onClick={() => handleButtonClick(30)}>近30天</Button>
                        <RangePicker
                            value={selectedRange}
                            allowClear = {false}
                            onChange={
                                (value) => {
                                    setSelectedRange(value);
                                }
                            }
                        />
                    </div>
                </div>
            </div>
            {
                tpyeList === '0' && <DataChart
                    datalistOne={datalistOne}
                    datalistTwo={datalistTwo}
                    datalistThr={datalistThr}
                    datalistFour={datalistFour}
                />
            }
            {
                tpyeList === '1' &&
                <DataTable
                    datalistOne={datalistOne}
                    datalistTwo={datalistTwo}
                    datalistThr={datalistThr}
                    datalistFour={datalistFour}
                />
            }
        </DataStaticPageBox>
    );
}

export default DataStaticdPage;